package com.library.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.library.bean.User;
import com.library.service.UserService;
import com.library.service.impl.UserServiceImpl;

@MultipartConfig
@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		UserService us = new UserServiceImpl();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String sex = request.getParameter("sex");
		String realName = request.getParameter("realName");
		String phone = request.getParameter("phone");
		int age = Integer.parseInt(request.getParameter("age"));
		//复制用户上传的头像
		Part part = request.getPart("headImg");
		String headImg = "";
		if(part == null ||part.getSize()>2*1024*1024 || !part.getContentType().contains("image")) {
			request.setAttribute("headMsg", "请选择2M以内的图片文件作为头像");
			request.getRequestDispatcher("register.jsp");
		}else {
			//设置 图片 保存的地址
//			String savePath = request.getServletContext().getRealPath("/headImgs/");
			String savePath = "C:/headImgs/";
			//获取一个 独一无二的文件名
			String fileName = new Date().getTime()+"_"+part.getSubmittedFileName();
			//上传文件 需要复制到服务器的真实路径（真实路径不在 Tomcat里，需要配置虚拟路径）
			part.write(savePath+fileName);
			//headImg 用于存 访问路径
			headImg = "/library/headImgs/"+fileName;
		}
		
		User user = new User(username,password,realName,sex,phone,age,headImg);
		int result = us.register(user);
		if(result == 1){
			response.sendRedirect("login.jsp");
		}else if(result == -1){
			request.setAttribute("msg", "-1");
			request.getRequestDispatcher("register.jsp").forward(request,response);
		}else if(result == -2){
			request.setAttribute("msg", "-2");
			request.getRequestDispatcher("register.jsp").forward(request,response);
		}
	}

}
